package Concurrent.Lock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author chenjunjie
 * @since 2018-08-14
 */
public class ReentrantReadWriteLockDemo {
    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    public void read(){
        try{
            //lock.readLock().lock();
            long start = System.currentTimeMillis();
            while(System.currentTimeMillis() - start <= 0.2) {
                System.out.println("获取锁" + Thread.currentThread().getName() + " " + System.currentTimeMillis());
            }
            try {
                Thread.sleep(1);
            } finally {
                //lock.readLock().unlock();
            }
        }catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void write(){
        try {
            lock.writeLock().lock();
            long start = System.currentTimeMillis();
            while(System.currentTimeMillis() - start <= 1) {
                System.out.println("获取写锁" + Thread.currentThread().getName() + " " + System.currentTimeMillis());
            }
            try {
             Thread.sleep(1000);
            } finally {
                lock.writeLock().unlock();
            }
         }catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读读共享测试
     */
    public static void readTest(){
        ReentrantReadWriteLockDemo demo = new ReentrantReadWriteLockDemo();
        new Thread(new Runnable() {
            @Override
            public void run() {
                demo.read();
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                demo.read();
            }
        }).start();
    }

    /**
     * 写写互斥
     */
    public static void writeTest(){
        ReentrantReadWriteLockDemo demo = new ReentrantReadWriteLockDemo();
        new Thread(new Runnable() {
            @Override
            public void run() {
                demo.write();
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                demo.write();
            }
        }).start();
    }

    /**
     * 写读互斥
     */
    public static void writeAndReadTest(){
        ReentrantReadWriteLockDemo demo = new ReentrantReadWriteLockDemo();
        new Thread(new Runnable() {
            @Override
            public void run() {
                demo.write();
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                demo.read();
            }
        }).start();
    }



    public static void main(String[] args) {
        readTest();
        //writeTest();
        //writeAndReadTest();
    }
}
